package com.sgkusbcamdemo;

import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;

import com.gkusbsdk.SZUSBSDK;
import com.qitianyong.selfclass.CONSTANT;
import com.qitianyong.selfclass.GKDevice;
import com.qitianyong.selfclass.HardDecoder;
import com.qitianyong.selfclass.LogUtils;

/**
 * Created by gy on 2017/4/24.
 */

public class ShowPreviewDataActivity extends BaseActivity implements SZUSBSDK.CallBack {

    private SurfaceView surface;
    private HardDecoder hardDecoder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        surface = new SurfaceView(this);
        setContentView(surface);
        ViewGroup.LayoutParams layoutParams = surface.getLayoutParams();
        layoutParams.width = 1080;
        layoutParams.height = 720;
        GKDevice.getInstance().setCallback(this);

        surface.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CaptureAndGetDataDialog captureAndGetDataDialog = new CaptureAndGetDataDialog(ShowPreviewDataActivity.this);
                captureAndGetDataDialog.getWindow().setDimAmount(0);  // 透明度 (0:完全透明 ~ 1:完全不透明)
                captureAndGetDataDialog.show();
            }
        });
        SurfaceHolder holder = surface.getHolder();
        holder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                hardDecoder = new HardDecoder(CONSTANT.MAX_WIDTH,
                        CONSTANT.MAX_HEIGHT, holder.getSurface());
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                if(hardDecoder!=null)
                    hardDecoder.Destroy();
            }
        });
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        GKDevice.getInstance().setCallback(null);
    }
    TimeUtil net_call = new TimeUtil("cb_stream");

    @Override
    public void cb_stream(long hUSBDevice, byte[] data, final int length, final int width, final int height, final int time) {
        net_call.call();
        if(hardDecoder != null) {
            hardDecoder.Decoder(data, length);
        }
    }
    class TimeUtil{
        String tag ;

        long time;
        int times;
        public TimeUtil(String tag) {
            this.tag = tag;
        }

        public void call() {
            long l = System.currentTimeMillis();
            if (time / 1000 != l / 1000) {
                time = l;
                LogUtils.d("TimeUtil", tag + "  " + times);
                times = 0;
            }
            times++;
        }
    }

}
